﻿using System;
using System.Reflection;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using NLog;

namespace RaytracerLib.Importers
{
    public class ColladaImporter
    {
        private Logger Logger = LogManager.GetCurrentClassLogger();

        public void SchemaValidate(string a_file)
        {
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                XmlReader xml_schema_reader =
                    XmlReader.Create(assembly.GetManifestResourceStream("Raytracer.Collada.xsd"));

                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(null, xml_schema_reader);
                settings.ValidationType = ValidationType.Schema;
                settings.ValidationEventHandler += SchemaValidationEventHandler;

                using (XmlReader xml_reader = XmlReader.Create(a_file, settings))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(xml_reader);
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }

        private void SchemaValidationEventHandler(object a_sender, ValidationEventArgs a_e)
        {
            Logger.Error("Validation Error Message: {0}", a_e.Message);
            Logger.Error("Validation Error Severity: {0}", a_e.Severity);

            if (a_e.Exception != null)
            {
                Logger.Error("Validation Error Line Number: {0}",
                        a_e.Exception.LineNumber);
                Logger.Error("Validation Error Line Position: {0}",
                        a_e.Exception.LinePosition);
                Logger.Error("Validation Error Source: {0}",
                        a_e.Exception.Source);
                Logger.Error("Validation Error Source Schema: {0}",
                        a_e.Exception.SourceSchemaObject);
                Logger.Error("Validation Error Source Uri: {0}",
                        a_e.Exception.SourceUri);
                Logger.Error("Validation Error thrown from: {0}",
                        a_e.Exception.TargetSite);
                Logger.Error("Validation Error callstack: {0}",
                        a_e.Exception.StackTrace);
            }
        }

        public Scene Import(string a_file)
        {
            try
            {
                Scene scene = new Scene();

                if (String.IsNullOrEmpty(a_file))
                    return scene;

                XDocument doc = XDocument.Load(a_file);

                return scene;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw;
            }
        }
    }
}